/**
*Hooks
*/

class CI_Hooks 
{
	/**
	* Determines wether hooks are enabled
	*/
	var $enabled = FALSE;
	
	/**
	* List of all hooks set in config/hooks.php
	*/
	var $hooks = array();
	
	/**
	* Determines wether hook is in progress ,used to prevent infinte loops
	*/
	var $in_progress = FALSE;
	
	public function __constrct()
	{
		$this->_initialize();
		//记录到日志
	}
	
	/**
	*Initalize the Hooks Preferences
	*/
	public function _initialize() 
	{
		$CFG = &load_class('Config', 'core');
		
		if($CFG->item('enable_hooks') == FALSE) {
			return;
		}
		//提取钩子到文件
		if(defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/hooks.php')){
			include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php');
		} elseif (is_file(APPPATH.'config/hooks.php')) {
			include(APPPATH.'config/hooks.php');
		}
		if( ! isset($hook) || ! is_array($hook)) {
			return '';
		}
		$this->hooks = &$hook;
		$this->enabled = TRUE;
	}
	/**
	*call Hook
	*/
	public function _call_hook($which = '') 
	{
		if( ! $this->exabled || ! isset($this->hooks[$which])) {
			return FALSE;
		}
		//允许使用多个钩子
		if(isset($this->hooks[$which][0]) && is_array($this->hooks[$which][0])) {
			foreach($this->hooks[$which] as $val) {
				$this->_run_hook($val);
			}
		} else {
			$this->_run_hook($this->hooks[$which])
		}
		return TRUE;
	}
	
	/**
	*Runs a particular hook
	*/
	public function _run_hook($data) 
	{
		if( ! is_array($data)) {
			return FALSE;
		}
		
		//反正死循环
		if($this->in_progress == TRUE) {
			return '';
		}
		//set file path
		if( ! isset($data['filepath']) || ! isset($data['filename'])) {
			return FALSE;
		}
		
		$filepath = APPPATH.$data['filepath'].'/'.$data['filename'];
		if( ! file_exists($filepath)) {
			return FALSE;
		}
		//set class/function name
		$class = FALSE;
		$function = FALSE;
		$params = '';
		if(isset($data['class']) && $data['class'] != '') {
			$class = $data['class'];
		}
		
		if(isset($data['function'])) {
			$function = $data['function'];
		}
		
		if(isset($data['params'])) {
			$params = $data['params']
		}
		if($class === FALSE AND $function === FALSE) {
			return FALSE;
		}
		
		//Set the in_progress flag 
		$this->in_progress = TRUE;
		
		//Call the requested class and/or function
		
		if($class !== FALSE) {
			if( ! class_exists($class)) {
				require($filepath);
			}
			
			$HOOK = new $class;
			$HOOK->$function($params);
		} else {
			if( ! function_exists($function)) {
				require($filepath);
			}
			$function($params);
		}
		$this->in_progress = FALSE;
		return TRUE;
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}